
class Content < Controller

  def index e
    s = ''
    s << '<center>'
    #s << '<h1>Obsah</h1>'
    s << (content_type_chooser e)
    s << '</center>'
    s
  end

  def content_type_chooser e
    s = ''
    ContentTemplate.all.each { |template|
      s << Element.new(:a,
        template.template_title,
        :href => e.link(:list)+"/#{template.id}",
        :class => :button
      ).to_s+ ' '
    }
    s
  end

  def list e

    if id = e.params['delete']
      Thing.get(id).destroy
    end

    t = ContentTemplate.get!(shift_tail e)
    s = ''
    s << '<center>'
    s << (content_type_chooser e)
    s << '<h1>'+t.template_title+'</h1>'
    
    s << '<p>'
    s << Element.new(:a, '+ přidej',
        :href => e.link('add?template='+t.id.to_s),
        :class => 'button'
      ).to_s
    s << '</p>'

    s << '<table class="content-list">'
    Thing.to_const(t.template_class).all.each { |instance|
      s << '<tr><td class="item">'
      s << Element.new(:a, instance.title,
        :href => e.link('edit/'+instance.id.to_s+'?template='+t.id.to_s)).to_s
      s << '</td><td>'

      s << Element.new(:a, 'smaž',
        :href => e.link('list/'+t.id.to_s+'?delete='+instance.id.to_s),
        :class => :button
      ).to_s

      s << '<td><tr/>'
    }
    s << '</table>'
    s << '</center>'
    s
  end

  def add e
    return add_thing e if e.params['template']
    s = '<h1>Přidat</h1>'
    s
  end

  def add_thing e
    template_id = e.params['template'].to_i
    template = ContentTemplate.get!(template_id)

    if !e.request.post?
      @thing = template.clone_thing
    end

    back = Element.new(:a,
        '&lt; zpět',
        :href => e.link(:list)+"/#{template.id}",
        :class => :button
      )

    <<HTML
<center>
  #{back}
  <h1>Přidat obsah</h1>
</center>
  #{@thing.creator_form e}
HTML
  end

  def edit e
    id = e.env[:unprocessed_tail][0].to_i
    
    template_class = Thing.to_const(Thing.all(:id => id).first.kind)
    edit = template_class.get!(id)

    template_id = e.params['template'].to_i
    #template = template_klass.get!(template_id)

    back = Element.new(:a,
      '&lt; zpět',
      :href => e.link(:list)+"/#{template_id}",
      :class => :button
    )

    <<HTML
<center>
  #{back}
</center>
  <br/>
  #{edit.creator_form e}
HTML
  end

end
